package com.tank.window;

import com.apple.eawt.Application;
import com.net.Client;
import com.tank.model.GameModel;
import javax.swing.*;
import java.awt.*;

import static java.lang.System.getProperty;


public class GameApplicationWindows extends JFrame {
    /**
     * 窗口宽度
     */
    public final static int WINDOWS_WIDTH = 800;
    /**
     * 窗口高度
     */
    public final static int WINDOWS_HEIGHT = 600;

    /**
     * 窗口ICON
     */
    private final static String WINDOWS_ICON = "resource/icon/game.png";
    /**
     * 窗口标题
     */
    private final static String WINDOWS_TITLE = "坦克";

    public final static GameApplicationWindows INSTANCE = new GameApplicationWindows();
    private static final long serialVersionUID = 196988649600959851L;

    /**
     * 双缓冲解决窗口绘制闪烁问题image
     */
    private Image offScreenImage;

    static {
        // 是mac 就设置dock图标
        if (getProperty("os.name").contains("Mac")) {
            // 指定mac 的dock图标
            Application.getApplication().setDockIconImage(new ImageIcon(WINDOWS_ICON).getImage());
        }
    }

    /**
     * 窗口初始化
     */
    private GameApplicationWindows() { }

    public static void run() {
        INSTANCE.setSize(WINDOWS_WIDTH, WINDOWS_HEIGHT);
        INSTANCE.setResizable(false);
        INSTANCE.setTitle(WINDOWS_TITLE);
        INSTANCE.setVisible(true);
        INSTANCE.setLocationRelativeTo(null);
        INSTANCE.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        INSTANCE.setIconImage(new ImageIcon(WINDOWS_ICON).getImage());

        new Thread(INSTANCE::updateWindows).start();
        Client.INSTANCE.connection();
    }

    public static GameApplicationWindows getInstance() {
        return INSTANCE;
    }

    /**
     * 重写repaint方法手动调用
     * update()方法
     */
    @Override
    public void repaint() {
        super.repaint();
        update(getGraphics());
    }

    /**
     * 绘制游戏，包括我方坦克以及敌方坦克
     *
     * @param graphics
     */
    @Override
    public void paint(Graphics graphics) {
        if (GameModel.getInstance() != null) {
            GameModel.getInstance().paint(graphics);
        }
    }

    /**
     * 重写update方法解决ui刷新闪烁问题
     *
     * @param graphics
     */
    @Override
    public void update(Graphics graphics) {
        if (offScreenImage == null) {
            offScreenImage = this.createImage(WINDOWS_WIDTH, WINDOWS_HEIGHT);
        }
        Graphics gOffScreen = offScreenImage.getGraphics();
        Color color = gOffScreen.getColor();
        gOffScreen.setColor(Color.WHITE);
        gOffScreen.fillRect(0, 0, WINDOWS_WIDTH, WINDOWS_HEIGHT);
        gOffScreen.setColor(color);
        paint(gOffScreen);
        graphics.drawImage(offScreenImage, 0, 0, null);
    }

    /**
     * 窗口视图刷新
     */
    public void updateWindows() {
        while (true) {
            repaint();
        }
    }
}
